<?php
/**
 * FileName: CodeService.php
 * Author: Fei.Song
 * Date: 2021/5/4 23:18
 * Created by PhpStorm
 * Desc:
 */

namespace App\Service;

use App\Models\Code;
use Illuminate\Support\Facades\Cache;

class CodeService extends BaseService {
    /**
     * @var string 代码缓存KEY
     */
    protected $cachePrefix = 'CODE_';

    /**
     * @var float|int 缓存有效期
     */
    protected $ttl = 60 * 60 * 24 * 5;//5天

    /**
     * 获取代码项列表
     * @param string $code 代码项代码
     * @return mixed
     */
    public function getItemsByCode($code) {
        return $this->get($code);
    }

    /**
     * 返回html字符串
     * @param string $code 代码项代码
     * @param string $selectCode 代码选中项
     * @param null $default 默认项
     * @return string html字符串(option)
     */
    public function getOptionsByCode($code, $selectCode = '', $default = null) {
        $items = $this->get($code);
        $html = '';

        if (!is_null($default)) {
            $html .= "<option value=\"\">{$default}</option>";
        }
        foreach ($items as $item) {
            if ($selectCode == $item['value']) {
                $html .= "<option value=\"{$item['value']}\" selected=\"selected\">{$item['name']}</option>";
            } else {
                $html .= "<option value=\"{$item['value']}\">{$item['name']}</option>";
            }
        }
        return $html;
    }

    /**
     * 根据代码值返回代码名称
     * @param string $code 代码项代码
     * @param string $value 代码值
     * @return mixed
     */
    public function name($code, $value) {
        $items = $this->get($code);
        return $items[$value]['name'] ?? '';
    }

    /**
     * 重新缓存
     * @param string $code
     */
    public function cache($code) {
        $this->set($code);
    }

    /**
     * 缓存设置
     * @param string $code
     * @return mixed
     */
    private function set($code) {
        $items = (new Code())->firstWhere('code', $code)->items()->toArray();

        Cache::put($this->cacheKey($code), $items, $this->ttl);
        return $items;
    }

    /**
     * 获取缓存
     * @param string $code
     * @return mixed
     */
    private function get($code) {
        $items = Cache::get($this->cacheKey($code));
        if (!$items) {
            $items = $this->set($code);
        }
        return $items;
    }

    private function cacheKey($code) {
        return $this->cachePrefix . $code;
    }
}